<template>
  <el-dialog
    v-model="dialogVisible"
    destroyOnClose
    top="12vh"
    :close-on-click-modal="false"
    append-to-body
    @close="close"
    title="数据源配置"
    width="850"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-form-item label="数据源名称" prop="serviceName">
        <el-input v-model="form.serviceName"></el-input>
      </el-form-item>
      <el-form-item label="数据源访问地址" prop="serviceUrl">
        <el-input v-model="form.serviceUrl"></el-input>
      </el-form-item>
      <el-form-item label="">
        <template #label>
          <div class="flex items-center">
            <span>token存放位置</span>
            <el-tooltip
              effect="dark"
              content="指在请求数据源接口时将token存放的位置,默认存放在请求头中"
              placement="top-start"
              ><el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div class="flex items-center">
          <div>{{ form.tokenParamJson.potition.label }}</div>
          <div
            @click="configPosition = true"
            class="ml-[25px] cursor-pointer text-[13px] text-[#69a9e9]"
          >
            去配置
          </div>
        </div>
      </el-form-item>
      <el-form-item label="token值">
        <el-radio-group
          class="mt-[-4px]"
          v-model="form.hasTokenVal"
          @change="changeTokenType"
        >
          <el-radio value="0" size="large">已有token</el-radio>
          <el-radio value="1" size="large">接口获取</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label=" " prop="tokenVal" v-show="form.hasTokenVal == '0'">
        <el-input
          type="textarea"
          placeholder="请输入token"
          v-model="form.tokenVal"
        ></el-input>
      </el-form-item>
    </el-form>
    <div v-show="form.hasTokenVal == '1'">
      <el-button type="primary" class="mb-[5px]" text disabled
        >配置Token请求接口详情</el-button
      >
      <ConfigToken
        :show="form.hasTokenVal"
        v-model:request="form.tokenParamJson"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="confirm">保存</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </template>

    <TokenPosition
      v-if="configPosition"
      @close="closePositon"
      :initState="form.tokenParamJson.potition"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { FormRules } from "element-plus";
import { ref, reactive, watch, nextTick } from "vue";
import ConfigToken from "./configToken.vue";
import TokenPosition from "./tokenPosition.vue";
import { filterTokenMethod } from "@renderer/utils/eventMethods";
import { emitter2 } from "@renderer/utils/event";
import {
  getDataSourceDetail,
  saveDataSource,
  updateDataSource,
} from "@renderer/api/dataSource";
let dialogVisible = ref(false);
let emit = defineEmits(["close", "updateData"]);
let configPosition = ref(false);
let formRef = ref(null);
const closePositon = (value: any) => {
  if (value) {
    form.value.tokenParamJson.potition = value;
  }
  configPosition.value = false;
};

const rules = reactive<FormRules<any>>({
  serviceName: [{ required: true, message: "数据源名称必填", trigger: "blur" }],
  serviceUrl: [
    { required: true, message: "数据源访问地址必填", trigger: "blur" },
  ],
  tokenVal: [{ required: true, message: "token值为必填", trigger: "blur" }],
  url: [{ required: true, message: "请求地址为必填", trigger: "blur" }],
});
let form = ref({
  serviceName: "", // 数据源名称
  serviceUrl: "", //  数据源接口地址
  tokenVal: "", // token值
  tokenUrl: "", // token请求接口地址
  hasTokenVal: "0",
  //token请求接口的配置信息们
  tokenParamJson: {
    baseUrl: "",
    url: "",
    method: "get",
    data: {},
    params: {},
    headers: {},
    filterKey: "",
    filterMethods: filterTokenMethod, // token请求接口字段筛选
    potition: {
      type: "Header",
      params: "Authorization",
      label: "请求头的Authorization字段中",
    }, // token值放在接口的哪个字段中
  },
});
watch(
  () => form.value.tokenParamJson,
  () => {
    form.value.tokenUrl = form.value.tokenParamJson.baseUrl;
  },
  { deep: true }
);
let type = ref("add");
const init = (types, id?) => {
  type.value = types;
  if (types == "edit") {
    getDataSourceDetail({ id }).then((res) => {
      let tokenParamJson = JSON.parse(
        JSON.stringify(JSON.parse(res.data.tokenParamJson))
      );
      res.data.tokenParamJson = null;
      form.value = null;

      // console.log("res", res.data);
      // console.log("form", form.value);
      // console.log("tokenParamJson", tokenParamJson);
      form.value = {
        ...res.data,
      };
      form.value.tokenParamJson = tokenParamJson;
      emitter2.emit("tokenParamJson", tokenParamJson);
      // console.log("form", form.value);
    });
  }
  if (types == "add") {
    form.value = {
      serviceName: "", // 数据源名称
      serviceUrl: "", //  数据源接口地址
      tokenVal: "", // token值
      tokenUrl: "", // token请求接口地址
      hasTokenVal: "0",
      //token请求接口的配置信息们
      tokenParamJson: {
        baseUrl: "",
        url: "",
        method: "get",
        data: {},
        params: {},
        headers: {},
        filterKey: "",
        filterMethods: filterTokenMethod, // token请求接口字段筛选
        potition: {
          type: "Header",
          params: "Authorization",
          label: "请求头的Authorization字段中",
        }, // token值放在接口的哪个字段中
      },
    };
  }
};

const changeTokenType = () => {
  // if (form.value.hasTokenVal == "1") {
  //   form.value.tokenVal = "";
  // }
};
const close = () => {
  dialogVisible.value = false;
};
const confirm = () => {
  formRef.value.validate((valid: any) => {
    if (!valid) {
      console.log("!");
    }
  });
  if (form.value.tokenVal == "" && form.value.tokenParamJson.url == "") {
    ElMessage.warning("token值或token请求接口路径必填一个");
    return;
  }
  let obj = {
    ...form.value,
    tokenParamJson: JSON.stringify(
      JSON.parse(JSON.stringify(form.value.tokenParamJson))
    ),
  };
  if (obj.hasTokenVal == "1") {
    obj.tokenVal = "";
  }
  console.log("obj", obj.tokenParamJson);
  if (type.value == "add") {
    saveDataSource(obj).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("保存成功");
        formRef.value.resetFields();
        emit("close");
        close();
      }
    });
  } else {
    updateDataSource(obj).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("保存成功");
        formRef.value.resetFields();
        emit("close");
        close();
      }
    });
  }

  // close();
};
defineExpose({
  dialogVisible,
  init,
  form,
});
</script>

<style scoped lang="scss"></style>
